/**   
 * @Title: MatchInfoAct.java 
 * @Package com.esun.cheetah.view.match.matchinfo
 * @Description: 比赛详情
 * @author 程相亭 <br/>
 * @date 2012-03-22 下午05:07:33  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.cheetah.view.match.matchinfo;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.match.matchinfo.MatchInfoCommunicater;
import com.esun.cheetah.biz.personal.attention.AddAttentionMatch;
import com.esun.cheetah.biz.personal.attention.AttentionListManager;
import com.esun.cheetah.biz.personal.attention.CancelAttenMatch;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.BizCode;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.IntentKey;
import com.esun.cheetah.config.Key;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.model.match.matchinfo.MatchInfoRealTimeBean;
import com.esun.cheetah.view.HomeAct;
import com.esun.cheetah.view.custom.CustomProgressDialog;
import com.esun.cheetah.view.personal.EventDetails;
import com.esun.util.Tools;
import com.esun.util.log.EDebug;
import com.esun.util.pngloader.AsyPngLoader;
import com.esun.util.pngloader.PngLoader;

/**
 * com.esun.cheetah.view.match.matchinfo.MatchInfoAct
 * 
 * @Description:比赛详情
 * @author 程相亭 <br/>
 * @date 2012-03-22 下午05:07:33
 */
public class MatchInfoAct extends Activity implements OnClickListener,
		OnCheckedChangeListener {

	private TextView tvMatchScreenings; // 场次
	private TextView tvMatchHomeRanking; // 主队排名
	private TextView tvMatchHomeScore; // 主队得分
	private TextView tvMatchHomeName;

	private TextView tvMatchGuestRanking; // 客队排名
	private TextView tvMatchGuestScore; // 客队得分
	private TextView tvMatchGuestName;

	private TextView tvMatchCurrentTime; // 当前时间
	private TextView tvHalfScore; // 半场比分

	private TextView tvWebviewFail; // webview加载失败

	private RadioGroup rgMatchinfoChange;

	private Button bntMatchGoBack; // 后退

	private ImageView ivMatchHome; // 主队图标
	private ImageView ivMatchGuest; // 客队图标
	private ImageView ivMatchHomeBG; // 主队图标范围
	private ImageView ivMatchGuestBG; // 客队图标范围
	private ImageView ivContact; // 关注
	private ImageView ivRefresh; // 刷新
	private ProgressBar pbRefresh; // 刷新
	private CustomProgressDialog progress;

	private FrameLayout bodyview; // webview容器
	private WebView wvAlive; // 实况
	private WebView wvStatistics; // 统计
	private WebView wvAnalysis; // 分析
	private WebView wvOdds; // 赔率
	private WebView wvBetting; // 投注

	private Thread refreshThread;
	private Handler handler;
	private Handler cancelContentHandler;
	private MatchInfoCommunicater matchInfoCommunicater; // 比赛详情
	private AddAttentionMatch addAttentionMatchCommunicater;// 添加关注
	private CancelAttenMatch cancelAttenMatchCommunicater; // 取消关注
	private MatchInfoRealTimeBean matchInfoRealTimeBean = new MatchInfoRealTimeBean();

	private int radioFlag = 0; // 实况
	public static boolean suspendFlag = true; // 线程暂停flag
	private static int webNum = 0;
	//private static boolean isFirstLoad = true ;

	private static final int REFRESH = 0X000000; // 计时刷新信息

	private static String matchId; // 赛事id
	private static String leagueRoundFinal; // 联赛轮次
	// 底部广告
	private ImageView footerView ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.match_info_common);
		changePushNumber();
		// 初始化；
		initHandler();
		initUi();
		getIntentParams();
		// 显示传递的参数
		getMatchInfo();
	}

	/**
	 * @Title: initUi
	 * @Description: UI初始化
	 * @param
	 * @return
	 * @throws
	 */
	public void initUi() {

		progress = new CustomProgressDialog(MatchInfoAct.this);
		progress.setMessage("加载数据中...");
		progress.show();
		progress.setCancelable(true);

		tvMatchScreenings = (TextView) findViewById(R.id.tv_matchinfo_realtime_match_screenings);
		tvMatchScreenings.setOnClickListener(this);
		tvMatchHomeRanking = (TextView) findViewById(R.id.tv_matchinfo_realtime_home_place_in_league_match);
		tvMatchHomeScore = (TextView) findViewById(R.id.tv_matchinfo_realtime_home_score);
		tvMatchHomeName = (TextView) findViewById(R.id.tv_matchinfo_realtime_home_name);
		tvMatchGuestRanking = (TextView) findViewById(R.id.tv_matchinfo_realtime_guest_place_in_league_match);
		tvMatchGuestScore = (TextView) findViewById(R.id.tv_matchinfo_realtime_guest_score);
		tvMatchGuestName = (TextView) findViewById(R.id.tv_matchinfo_realtime_guest_name);
		tvMatchCurrentTime = (TextView) findViewById(R.id.tv_matchinfo_realtime_current_time);
		tvHalfScore = (TextView) findViewById(R.id.tv_matchinfo_realtime_half_score);
		tvWebviewFail = new TextView(MatchInfoAct.this);
		tvWebviewFail.setText("暂无数据");
		tvWebviewFail.setGravity(Gravity.CENTER);

		rgMatchinfoChange = (RadioGroup) findViewById(R.id.rg_matchinfo_realtime_change_button);
		rgMatchinfoChange.setOnCheckedChangeListener(this);

		bntMatchGoBack = (Button) findViewById(R.id.btn_matchinfo_realtime_goback);
		bntMatchGoBack.setOnClickListener(this);
		//btnMatchLottery.setOnClickListener(this);

		ivMatchHome = (ImageView) findViewById(R.id.iv_matchinfo_home);
		ivMatchHomeBG = (ImageView) findViewById(R.id.iv_matchinfo_home_bg);
		ivMatchHomeBG.setOnClickListener(this);
		ivMatchGuestBG = (ImageView) findViewById(R.id.iv_matchinfo_guest_bg);
		ivMatchGuest = (ImageView) findViewById(R.id.iv_matchinfo_guest);
		ivMatchGuestBG.setOnClickListener(this);
		ivContact = (ImageView) findViewById(R.id.iv_matchinfo_contact);
		ivContact.setOnClickListener(this);
		ivRefresh = (ImageView) findViewById(R.id.iv_matchinfo_realtime_refresh);
		pbRefresh = (ProgressBar) findViewById(R.id.pb_matchinfo_realtime_refresh);
		ivRefresh.setOnClickListener(this);
		setProgressBarGone();
		
		footerView = (ImageView)findViewById(R.id.iv_matchinfo_footer_img) ;
		footerView.setOnClickListener(this) ;

		bodyview = (FrameLayout) findViewById(R.id.fl_matchinfo_bodyview);
		wvAlive = new WebView(MatchInfoAct.this);
		wvStatistics = new WebView(MatchInfoAct.this);
		wvAnalysis = new WebView(MatchInfoAct.this);
		wvOdds = new WebView(MatchInfoAct.this);
		wvBetting = new WebView(MatchInfoAct.this);
		wvAlive.setWebViewClient(new HelloWebViewClient());
		wvStatistics.setWebViewClient(new HelloWebViewClient());
		wvAnalysis.setWebViewClient(new HelloWebViewClient());
		wvOdds.setWebViewClient(new HelloWebViewClient());
		wvBetting.setWebViewClient(new HelloWebViewClient());
		wvAlive.getSettings().setJavaScriptEnabled(true);
		wvStatistics.getSettings().setJavaScriptEnabled(true);
		wvAnalysis.getSettings().setJavaScriptEnabled(true);
		wvOdds.getSettings().setJavaScriptEnabled(true);
		wvBetting.getSettings().setJavaScriptEnabled(true);

		wvAlive.setBackgroundResource(R.drawable.anull_icon);
		wvStatistics.setBackgroundResource(R.drawable.anull_icon);
		wvAnalysis.setBackgroundResource(R.drawable.anull_icon);
		wvOdds.setBackgroundResource(R.drawable.anull_icon);
		wvBetting.setBackgroundResource(R.drawable.anull_icon);

		// 避免2.1以下的版本android.webkit.BrowerFrame出现保存密码是的空指针错误
		wvAlive.getSettings().setSavePassword(false);
		wvStatistics.getSettings().setSavePassword(false);
		wvAnalysis.getSettings().setSavePassword(false);
		wvOdds.getSettings().setSavePassword(false);
		wvBetting.getSettings().setSavePassword(false);

		wvAlive.getSettings().setSaveFormData(false);
		wvStatistics.getSettings().setSaveFormData(false);
		wvAnalysis.getSettings().setSaveFormData(false);
		wvOdds.getSettings().setSaveFormData(false);
		wvBetting.getSettings().setSaveFormData(false);

		// 除去webview滚动条及白色底框
		wvAlive.setVerticalScrollBarEnabled(false);
		wvStatistics.setVerticalScrollBarEnabled(false);
		wvAnalysis.setVerticalScrollBarEnabled(false);
		wvOdds.setVerticalScrollBarEnabled(false);
		wvBetting.setVerticalScrollBarEnabled(false);

		wvAlive.setBackgroundColor(0);
		wvStatistics.setBackgroundColor(0);
		wvAnalysis.setBackgroundColor(0);
		wvOdds.setBackgroundColor(0);
		wvBetting.setBackgroundColor(0);

	}

	/**
	 * @Title: initHandler
	 * @Description: Handler初始化
	 * @param
	 * @return
	 * @throws
	 */
	public void initHandler() {

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {

				case Config.COMMUNICATER_SUCCESS:
					matchInfoRealTimeBean = matchInfoCommunicater
							.getMatchInfoRealTimeBean();
					EDebug.o(matchInfoRealTimeBean, true);
					getMatchInfoSuccess(matchInfoRealTimeBean);

					break;

				case Config.COMMUNICATER_FAIL:
					EDebug.o("获取信息失败。。" + matchInfoCommunicater.getServerMsg());
					matchInfoFail();
					break;

				case Config.COMMUNICATER_EXCEPTION:
					matchInfoFail();
					Toast.makeText(MatchInfoAct.this, "网络出错，请重试",
							Toast.LENGTH_SHORT).show();
					EDebug.o("通讯异常！！！");
					break;

				case REFRESH:
					getMatchInfo();
					break;

				// 收藏成功
				case Config.COMMON_INFO_MSG_20001:
					attentationSuccess();
					break;

				// 收藏失败
				case Config.COMMON_INFO_MSG_20002:
					attentationFail();
					break;

				// 收藏失败
				case Config.COMMON_INFO_MSG_20003:
					attentationException();
					break;

				default:
					break;
				}
			}
		};

		cancelContentHandler = new Handler() {

			@Override
			public void dispatchMessage(Message msg) {
				super.dispatchMessage(msg);

				switch (msg.what) {
				// 取消收藏成功
				case Config.COMMUNICATER_SUCCESS:
					cancelAttentationSuccess();
					break;

				// 取消收藏失败
				case Config.COMMUNICATER_FAIL:
					cancelAttentationFail();
					break;

				// 取消收藏异常
				case Config.COMMUNICATER_EXCEPTION:
					cancleAttentationException();
					break;

				default:
					break;
				}
			}

		};
	}

	/**
	 * @Title: getMatchInfo
	 * @Description: 获取实况信息
	 * @param
	 * @return
	 * @throws
	 */
	public void getMatchInfo() {

		if (Tools.networkStatus(MatchInfoAct.this)) {
			setProgressBarShow();
			matchInfoCommunicater = new MatchInfoCommunicater(handler, matchId);
			matchInfoCommunicater.startCommunicate();
		} else {
			matchInfoFail();
		}
	}

	/**
	 * @Title: matchInfoFail
	 * @Description:比赛信息失败操作
	 * @param
	 * @return
	 * @throws
	 */
	public void matchInfoFail() {
		setProgressBarGone();
		if (progress.isShowing()) {
			progress.dismiss();
		}
		// pbRefreshWv.setVisibility(View.INVISIBLE) ;
		bodyview.removeAllViews();
		bodyview.addView(tvWebviewFail, LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
	}

	/**
	 * @Title: attentationSuccess
	 * @Description:收藏成功操作
	 * @param
	 * @return
	 * @throws
	 */
	public void attentationSuccess() {
		ivContact.setImageResource(R.drawable.iv_added_team_selector);
		matchInfoRealTimeBean.isGuanzhu = "1";
		//MatchListManager.getInstance().updateAttentionState(matchId, true);
		Toast.makeText(MatchInfoAct.this, "关注成功", Toast.LENGTH_SHORT).show();
	}

	/**
	 * @Title: attentationFail
	 * @Description:收藏失败操作
	 * @param
	 * @return
	 * @throws
	 */
	public void attentationFail() {
		ivContact.setImageResource(R.drawable.iv_add_team_selector);
		Toast.makeText(MatchInfoAct.this, "添加关注失败", Toast.LENGTH_SHORT).show();
	}

	/**
	 * @Title: attentationException
	 * @Description:收藏失败操作
	 * @param
	 * @return
	 * @throws
	 */
	public void attentationException() {
		ivContact.setImageResource(R.drawable.iv_add_team_selector);
		Toast.makeText(MatchInfoAct.this, "添加关注失败，请检查您的网络", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * @Title: cancelAttentationSuccess
	 * @Description:取消收藏操作成功
	 * @param
	 * @return
	 * @throws
	 */
	public void cancelAttentationSuccess() {
		ivContact.setImageResource(R.drawable.iv_add_team_selector);
		matchInfoRealTimeBean.isGuanzhu = "0";
		//MatchListManager.getInstance().updateAttentionState(matchId, false);
		AttentionListManager.getInstance().updateCancelAttention(matchId);
		Toast.makeText(MatchInfoAct.this, "取消关注成功", Toast.LENGTH_SHORT).show();
	}

	/**
	 * @Title: cancelAttentationFail
	 * @Description:取消收藏异常失败
	 * @param
	 * @return
	 * @throws
	 */
	public void cancelAttentationFail() {
		//ivContact.setBackgroundResource(R.drawable.iv_added_team_selector);
		ivContact.setImageResource(R.drawable.iv_added_team_selector) ;
		Toast.makeText(MatchInfoAct.this, "取消关注失败", Toast.LENGTH_SHORT).show();
	}

	/**
	 * @Title: cancleAttentationException
	 * @Description:取消收藏异常
	 * @param
	 * @return
	 * @throws
	 */
	public void cancleAttentationException() {
		ivContact.setImageResource(R.drawable.iv_added_team_selector);
		Toast.makeText(MatchInfoAct.this, "取消关注失败，请检查您的网络", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * @Title: getIntentParams
	 * @Description: 获取传递参数
	 * @param
	 * @return
	 * @throws
	 */
	public void getIntentParams() {

		matchId = (String) getIntent().getExtras().get(IntentKey.INTENT_KEY_MATCH_ID) ;
		
	}

	/**
	 * @Title: getMatchInfoSuccess
	 * @Description: 获取实况信息成功处理
	 * @param MatchInfoRealTimeBean
	 *            实况信息Bean
	 * @return
	 * @throws
	 */
	public void getMatchInfoSuccess(MatchInfoRealTimeBean matchInfoRealTimeBean) {

		setProgressBarGone();

		if (matchInfoRealTimeBean.matchRound.equals(BizCode.ZERO)) {
			leagueRoundFinal = matchInfoRealTimeBean.simplegbName
					+ matchInfoRealTimeBean.stageName;
		} else {
			leagueRoundFinal = matchInfoRealTimeBean.simplegbName
					+ Language.MSG_DI + matchInfoRealTimeBean.matchRound
					+ Language.MSG_LUN;
		}
		tvMatchScreenings.setText(leagueRoundFinal);
		tvMatchHomeRanking.setText(Language.SPEC_LEFT_CURVE + matchInfoRealTimeBean.homeStanding + Language.SPEC_RIGHT_CURVE);
		tvMatchGuestRanking.setText(Language.SPEC_LEFT_CURVE + matchInfoRealTimeBean.awayStanding + Language.SPEC_RIGHT_CURVE);

		if (matchInfoRealTimeBean.homeName.length() > 4) {
			tvMatchHomeName.setText(matchInfoRealTimeBean.homeName.substring(0,
					4));
		} else if (matchInfoRealTimeBean.homeName.length() == 2) {
			tvMatchHomeName.setText(matchInfoRealTimeBean.homeName.substring(0,
					1)
					+ "     "
					+ matchInfoRealTimeBean.homeName.substring(1, 2));
		} else if (matchInfoRealTimeBean.homeName.length() == 3) {
			tvMatchHomeName.setText(matchInfoRealTimeBean.homeName.substring(0,
					1)
					+ "  "
					+ matchInfoRealTimeBean.homeName.substring(1, 2)
					+ "  " + matchInfoRealTimeBean.homeName.substring(2, 3));
		} else {
			tvMatchHomeName.setText(matchInfoRealTimeBean.homeName);
		}
		if (matchInfoRealTimeBean.guestName.length() > 4) {
			tvMatchGuestName.setText(matchInfoRealTimeBean.guestName.substring(
					0, 4));
		} else if (matchInfoRealTimeBean.guestName.length() == 2) {
			tvMatchGuestName.setText(matchInfoRealTimeBean.guestName.substring(
					0, 1)
					+ "     "
					+ matchInfoRealTimeBean.guestName.substring(1, 2));
		} else if (matchInfoRealTimeBean.guestName.length() == 3) {
			tvMatchGuestName.setText(matchInfoRealTimeBean.guestName.substring(
					0, 1)
					+ "  "
					+ matchInfoRealTimeBean.guestName.substring(1, 2)
					+ "  "
					+ matchInfoRealTimeBean.guestName.substring(2, 3));
		} else {
			tvMatchGuestName.setText(matchInfoRealTimeBean.guestName);
		}
		if (!matchInfoRealTimeBean.status.equals("0") && !matchInfoRealTimeBean.status.equals("6")) {
			tvMatchHomeScore.setText(matchInfoRealTimeBean.homeScore);
			tvMatchGuestScore.setText(matchInfoRealTimeBean.guestScore);
		}
		if (matchInfoRealTimeBean.isGuanzhu.equals("1")) {
			ivContact
					.setImageResource(R.drawable.iv_added_team_selector);
		} else {
			ivContact.setImageResource(R.drawable.iv_add_team_selector);
		}

		// 设置顶部显示及比分牌状态
		if (matchInfoRealTimeBean.status.equals("0")) {
			tvMatchCurrentTime
					.setText(getResources().getString(R.string.title_kaisai)
							+ " "
							+ (matchInfoRealTimeBean.startTime
									.split(Config.ONESPACE))[1]);
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
		} else if (matchInfoRealTimeBean.status.equals("1")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_shangbanchang)
					+ matchInfoRealTimeBean.lastTime + "'");
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
		} else if (matchInfoRealTimeBean.status.equals("3")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_xiabanchang)
					+ matchInfoRealTimeBean.lastTime + "'");
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
		} else if (matchInfoRealTimeBean.status.equals("4")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_wanchang));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_end);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_end);
		} else if (matchInfoRealTimeBean.status.equals("2")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_zhongchang));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
		} else if (matchInfoRealTimeBean.status.equals("5")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_quxiao));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_end);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_end);
		} else if (matchInfoRealTimeBean.status.equals("6")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_gaiqi));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
		} else if (matchInfoRealTimeBean.status.equals("7")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_yaozhan));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_end);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_end);
		} else if (matchInfoRealTimeBean.status.equals("8")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_zhongduan));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_ing);
		} else if (matchInfoRealTimeBean.status.equals("9")) {
			tvMatchCurrentTime.setText(getResources().getString(
					R.string.title_daiding));
			tvMatchHomeScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
			tvMatchGuestScore
					.setBackgroundResource(R.drawable.img_default_score_soon);
		}

		tvHalfScore.setText(getResources().getString(R.string.title_banchang)
				+ matchInfoRealTimeBean.homeHalfScore + " : "
				+ matchInfoRealTimeBean.guestHalfScore);

		// 加载队标
		loadLogo(ivMatchHome, matchInfoRealTimeBean.homeSign);
		loadLogo(ivMatchGuest, matchInfoRealTimeBean.guestSign);
		
		wvAlive.loadUrl(Config.ALIVE_ADDRESS + matchId);
		wvStatistics.loadUrl(Config.STATISTICS_ADDRESS + matchId);
		wvAnalysis.loadUrl(Config.ANALYSIS_ADDRESS + matchId);
		wvOdds.loadUrl(Config.ODDS_ADDRESS + matchId + "&type=zq");
		wvBetting.loadUrl(Config.BETTING_ADDRESS + matchId);
		
//		switch (radioFlag) {
//		case 0 :
//			wvAlive.loadUrl(Config.ALIVE_ADDRESS + matchId);
//			break ;
//		case 1 :
//			wvStatistics.loadUrl(Config.STATISTICS_ADDRESS + matchId);
//			break ;
//		case 2 :
//			wvAnalysis.loadUrl(Config.ANALYSIS_ADDRESS + matchId);
//			break ;
//		case 3 :
//			wvOdds.loadUrl(Config.ODDS_ADDRESS + matchId + "&type=zq");
//			break ;
//		case 4 :
//			wvBetting.loadUrl(Config.BETTING_ADDRESS + matchId);
//			break ;
//		default :
//			break ;
//		
//		}

		loadWebView();

		refreshThread.interrupt();

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.btn_matchinfo_realtime_goback:
			 if (HomeAct.class != null && HomeAct.isActive) {
			 this.finish() ;
			
			 } else {
			 startActivity(new Intent(MatchInfoAct.this, HomeAct.class)) ;
			 this.finish() ;
			 }
			this.finish();

			break;

//		case R.id.btn_matchinfo_realtime_lottery:
//
//			intentToSportteryFootball = new Intent();
//			intentToSportteryFootball
//					.setClass(
//							MatchInfoAct.this,
//							com.esun.cheetah.view.personal.sportlotteryfootball.SportteryFootballAgp.class);
//			bundleToSportteryFootbal = new Bundle();
//			bundleToSportteryFootbal.putInt("CURRENT_TAB_NUM", 0);
//			intentToSportteryFootball.putExtras(bundleToSportteryFootbal);
//			startActivity(intentToSportteryFootball);
//
//			break;
			
		case R.id.iv_matchinfo_footer_img :
			Toast.makeText(this, "活动跳转", Toast.LENGTH_SHORT).show() ;
			break ;

		case R.id.iv_matchinfo_contact:
			doContact();
			break;

		// 刷新操作
		case R.id.iv_matchinfo_realtime_refresh:
			progress.show();
			getMatchInfo();
			break;

		case R.id.iv_matchinfo_home_bg:

			if (matchInfoRealTimeBean.homeTeamId != null
					&& !matchInfoRealTimeBean.homeTeamId.equals("")
					&& matchInfoRealTimeBean.homeName != null
					&& !matchInfoRealTimeBean.homeName.equals("")) {

				startActivity(new Intent()
						.setClass(MatchInfoAct.this, EventDetails.class)
						.putExtra(Config.TEAM_NAME,
								matchInfoRealTimeBean.homeName)
						.putExtra(Config.TEAM_ID,
								matchInfoRealTimeBean.homeTeamId)
						.putExtra(Config.TEAM_LEAGUE,
								matchInfoRealTimeBean.simplegbName));

			}

			break;

		case R.id.iv_matchinfo_guest_bg:
			if (matchInfoRealTimeBean.awayTeamId != null
					&& !matchInfoRealTimeBean.awayTeamId.equals("")
					&& matchInfoRealTimeBean.guestName != null
					&& !matchInfoRealTimeBean.guestName.equals("")) {
				startActivity(new Intent()
						.setClass(MatchInfoAct.this, EventDetails.class)
						.putExtra(Config.TEAM_ID,
								matchInfoRealTimeBean.awayTeamId)
						.putExtra(Config.TEAM_NAME,
								matchInfoRealTimeBean.guestName)
						.putExtra(Config.TEAM_LEAGUE,
								matchInfoRealTimeBean.simplegbName));
			}
			break;

		default:
			break;
		}
	}

	/**
	 * @Title: doContact
	 * @Description: 关注操作
	 * @param
	 * @return
	 * @throws
	 */
	public void doContact() {
		if (UserInfo.getUserInfo().getCk().equals(Config.NULLMARK)
				|| null == UserInfo.getUserInfo().getCk()) {
			Toast.makeText(MatchInfoAct.this, "请登录后添加关注的比赛", Toast.LENGTH_SHORT)
					.show();
		} else {
			if (matchId != null && !matchId.equals("")
					&& matchInfoRealTimeBean.isGuanzhu.equals("0")) {
				// 收藏操作
				addAttentionMatchCommunicater = new AddAttentionMatch(handler,
						UserInfo.getUserInfo().getUserName(), Key.ZQ, matchId,
						matchInfoRealTimeBean.homeName,
						matchInfoRealTimeBean.guestName,
						matchInfoRealTimeBean.startTime);
				addAttentionMatchCommunicater.startCommunicate();
			} else {
				// 收藏取消操作
				if (matchId != null && !matchId.equals("")
						&& matchInfoRealTimeBean.isGuanzhu.equals("1")) {
					cancelAttenMatchCommunicater = new CancelAttenMatch(
							cancelContentHandler, matchId);
					cancelAttenMatchCommunicater.startCommunicate();
				}
			}
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		switch (checkedId) {
		// 实况
		case R.id.ib_matchinfo_realtime:
			onPageChange(0);

			break;

		case R.id.ib_matchinfo_technical_statistics:
			onPageChange(1);

			break;

		case R.id.ib_matchinfo_analysis:
			onPageChange(2);

			break;

		case R.id.ib_matchinfo_odds:
			onPageChange(3);

			break;

		case R.id.ib_matchinfo_betting_data:
			onPageChange(4);

			break;

		default:
			break;
		}
	}

	/**
	 * @Title: onPageChange
	 * @Description: 页面切换事件
	 * @param
	 * @return
	 * @throws
	 */
	private void onPageChange(int flag) {
		if (Tools.networkStatus(MatchInfoAct.this)) {
			radioFlag = flag;
			loadWebView();
		} else {
			matchInfoFail();
		}
	}

	/**
	 * @Title: loadLogo
	 * @Description: 加载球队Logo
	 * @param
	 * @return
	 * @throws
	 */
	private void loadLogo(ImageView ivLogo, String url) {

		PngLoader loader = new PngLoader();
		// 加载主队LOGO
		AsyPngLoader homeAsyPngLoader = new AsyPngLoader(ivLogo);
		Drawable home = loader.getPng(url, homeAsyPngLoader);
		if (home != null) {
			EDebug.o("*********************1**************************");
			ivLogo.setImageDrawable(home);
		}
	}

	/**
	 * @Title: loadWebViewAnalysis
	 * @Description: 加载分析,赔率，数据界面
	 * @param
	 * @return
	 * @throws
	 */
	private void loadWebView() {
		// 设置Web视图
		switch (radioFlag) {
		case 0:
			bodyview.removeAllViews();
			bodyview.addView(wvAlive, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			footerViewGone() ;
			EDebug.o("实况url：" + Config.ALIVE_ADDRESS + matchId);
			break;
		case 1:
			bodyview.removeAllViews();
			bodyview.addView(wvStatistics, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			footerViewGone() ;
			EDebug.o("统计url：" + Config.ALIVE_ADDRESS + matchId);
			break;
		case 2:
			bodyview.removeAllViews();
			bodyview.addView(wvAnalysis, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			footerViewGone() ;
			EDebug.o("分析url：" + Config.ANALYSIS_ADDRESS + matchId);
			break;
		case 3:
			bodyview.removeAllViews();
			bodyview.addView(wvOdds, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			footerViewGone() ;
			EDebug.o("赔率url：" + Config.ODDS_ADDRESS + matchId + "&type=zq");
			break;
		case 4:
			bodyview.removeAllViews();
			bodyview.addView(wvBetting, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
			footerViewVisible() ;
			EDebug.o("同住数据url：" + Config.BETTING_ADDRESS + matchId);
			break;
		default:
			break;
		}

	}

	// Web视图
	private class HelloWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (url.startsWith("http://") && getRespStatus(url) == 404) {
				EDebug.o("加载webview出错。。。。");
				view.stopLoading();
				bodyview.removeAllViews();
				bodyview.addView(tvWebviewFail, LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT);
			} else {
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			webNum++;
			EDebug.o("------------------------------------>" + webNum);
			if (webNum == 5) {
				loadWebView() ;
				webNum = 0;
				if (progress.isShowing()) {
					progress.dismiss();
				}
			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			if (progress.isShowing()) {
				progress.dismiss();
			}
			bodyview.removeAllViews();
			bodyview.addView(tvWebviewFail, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);
		}
	}

	/**
	 * @Title: getRespStatus
	 * @Description: 获取加载url状态
	 * @param
	 * @return
	 * @throws
	 */
	private int getRespStatus(String url) { 
		int status = -1;
		try {
			HttpHead head = new HttpHead(url);
			HttpClient client = new DefaultHttpClient();
			HttpResponse resp = client.execute(head);
			status = resp.getStatusLine().getStatusCode();
		} catch (IOException e) {
		}
		return status;
	}

	/**
	 * @Title: setProgressBarGone
	 * @Description: 设置进度条不可见
	 * @param
	 * @return
	 * @throws
	 */
	private void setProgressBarGone() {
		pbRefresh.setVisibility(View.GONE);
		ivRefresh.setVisibility(View.VISIBLE);
	}

	/**
	 * @Title: setProgressBarShow
	 * @Description: 设置进度条可见
	 * @param
	 * @return
	 * @throws
	 */
	private void setProgressBarShow() {
		pbRefresh.setVisibility(View.VISIBLE);
		ivRefresh.setVisibility(View.GONE);
	}

	@Override
	protected void onResume() {

		EDebug.o("flag changed:" + suspendFlag);
		// 启动刷新线程
		suspendFlag = true;
		refreshThread = new Thread(new RefreshThread());
		refreshThread.start();
		super.onResume();
	}

	@Override
	protected void onPause() {
		suspendFlag = false;
		EDebug.o("flag changed:" + suspendFlag);
		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			webNum = 0;
			EDebug.o("dialog 消失....webNum-->" + webNum);
			if (progress.isShowing()) {
				EDebug.o("dialog 消失....");
				progress.dismiss();
			} else {
				if (HomeAct.class != null && HomeAct.isActive) {
					 	this.finish() ;
					 } else {
					 startActivity(new Intent(MatchInfoAct.this, HomeAct.class)) ;
					 	this.finish() ;
			}
		}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void footerViewGone () {
		footerView.setVisibility(View.GONE) ;
	}
	
	public void footerViewVisible () {
		footerView.setVisibility(View.VISIBLE) ;
	}

	/**
	 * 
	 * @Title: timeCountThread
	 * @Description: 计时线程
	 * @param
	 * @return
	 * @throws
	 */
	class RefreshThread implements Runnable {

		@Override
		public void run() {
			while (suspendFlag) {
				try {
					Thread.sleep(Config.REFRESH_TERM);
					// 判断标志位，防止此时flag已经改变
					if (suspendFlag) {
						Message msg = new Message();
						msg = handler.obtainMessage(REFRESH);
						handler.sendMessage(msg);
						EDebug.o("currentTime::::" + System.currentTimeMillis());
					}

				} catch (InterruptedException e) {
					EDebug.o("重新睡"+Config.REFRESH_TERM +"秒：" + System.currentTimeMillis());
					continue;
				}
			}
		}

	}

	private void changePushNumber() {
		SharedPreferences preference = getSharedPreferences(Config.PUSH_NUMBER,
				Context.MODE_PRIVATE);
		int number = preference.getInt(Config.PUSH_ACCOUNT, 1);
		if (number > 1) {
			number = number - 1;
			preference.edit().putInt(Config.PUSH_ACCOUNT, number).commit();
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (progress.isShowing()) {
			progress.dismiss();
		}
	}
}
